package com.aztec.ims.service.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

import com.aztec.ims.domain.CustomInfoMetaData;
import com.aztec.ims.service.om.CustomInfoMeta;
import com.aztec.ims.service.response.GenericResponse;
import com.aztec.ims.service.util.HibernateUtil;

public class CustomInfoMetadataDao {
	public GenericResponse createCustomMetaInfo(CustomInfoMetaData request) {
		CustomInfoMeta om = convertRequestToOm(request);

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(om);
		session.getTransaction().commit();

		GenericResponse response = new GenericResponse(om.getCustomInfoId()
				.toString());
		return response;
	}

	public List<CustomInfoMetaData> getCustomMetaInfo() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Criteria criteria = session.createCriteria(CustomInfoMeta.class);
		criteria.addOrder(Order.asc("customInfoId"));
		List results = criteria.list();
		session.getTransaction().commit();

		return convertOmToResponse(results);

	}

	private List<CustomInfoMetaData> convertOmToResponse(List results) {
		List<CustomInfoMetaData> response = new ArrayList<CustomInfoMetaData>();

		if (results != null) {
			for (Iterator iter = results.iterator(); iter.hasNext();) {
				CustomInfoMeta om = (CustomInfoMeta) iter.next();
				CustomInfoMetaData domain = new CustomInfoMetaData(om
						.getCustomInfoId().toString(), om.getFieldName(),om.getFieldType().toString());
				response.add(domain);
			}
		}

		return response;
	}

	private CustomInfoMeta convertRequestToOm(
			CustomInfoMetaData request) {

		CustomInfoMeta om = new CustomInfoMeta();
		om.setFieldName(request.getFieldName());
		if(request.getFieldType()!= null){
			Character fieldType = new Character(request.getFieldType().charAt(0));
			om.setFieldType(fieldType);	
		}
		return om;
	}

}
